#pragma once

#include "Task.hpp"
#include "Thread.hpp"
#include "lockGuard.hpp"
#include <pthread.h>
#include <vector>
#include <queue>
#include <iostream>

static const int gnum = 5;

template<class T>
class ThreadPool
{
public:
    ThreadPool(const int num = gnum):_cap(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    pthread_mutex_t* getlock()
    {
        return &_mutex;
    }
    void threadWait()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void threadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    bool isEmpty()
    {
        return _tasks.empty();
    }
    void pushTask(const T& t)
    {
        LockGuard lockguard(&_mutex);
        _tasks.push(t);
        threadWakeup();
    }
    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }
    static void threadRoutine(void* args)
    {
        // pthread_detach(pthread_self());
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*>(args);
        while (true)
        {
            T t;
            {
                LockGuard lockguard(tp->getlock());
                while (tp->isEmpty())
                {
                    tp->threadWait();
                }
                t = tp->popTask();
            }
            t();
            std::cout << "thread handler done, result: " << t.formatRes() << std::endl;
        }
    }
    void init()
    {
        // TODO
        for (int i = 0; i < _cap; ++i)
        {
            _thread.push_back(Thread(i, threadRoutine, this));
        }
    }
    void start()
    {
        for (auto& t : _thread)
        {
            t.run();
        }
    }
    void check()
    {
        for (auto &t : _thread)
        {
            std::cout << t.name() << " running..." << std::endl;
        }
    }
    ~ThreadPool()
    { 
        for (auto& t : _thread)
        {
            t.join();
        }
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
private:
    std::vector<Thread> _thread;
    int _cap;
    std::queue<T> _tasks;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};